<?php

require_once PATH_FFWD.'core/baseobject.class.php';
require_once PATH_FFWD.'core/exceptions.php';

class LT{//layout Target
	private $tagname='span';
	public function __construct($s){
		$s=explode('[',$s);
		$this->tagname=array_shift($s);
		echo '<'.$this->tagname;
		for($i=0;$i<count($s);$i++){
			if( (substr($s[$i],-1)!=']') || (strpos('=',$s[$i])==-1 ) ) throw new Exception('wrong LT-string format');
			$s[$i]=explode('=',$s[$i]);
			echo ' '.$s[$i][0].'="'.substr($s[$i][1],0,-1).'"';			
		};
		echo '>';	
	} 
	
	public function __destruct(){
		echo '</'.$this->tagname.'>';
	}
}

class BaseModule extends BaseObject{
	public		$table=NULL;
	protected $tplpath;
	protected $file;
	protected $config=Array();
	
	public function __construct($p){
		global $app;
		$trace=debug_backtrace();
		$p=strpos($trace[0]['file'],'\\apps\\');
		$this->file=str_replace('\\','/',substr($trace[0]['file'],$p+6));
		$this->tplpath=FFWD::getTplPathFromModuleFN($this->file);
		/*
		if($this->tplpath){
			try{
				if(!is_dir($this->tplpath))
					mkdir($this->tplpath,777,1);
			}catch(Exception $e){
				exit;
			}
		};/**/
		parent::__construct($p);
	}
	
	public function getTable(){
		return $this->table;
	}
	
	public function redirectTo($p){
		//echo h1($p);exit;
		return $GLOBALS['app']->redirectTo($p);
	}
	
	public function redirectLast($p=NULL){
		return $GLOBALS['app']->redirectLast($p);
	}
	
	public function showAction($p){
		print_var($p,"BaseModule::showAction()");
	}
	
	public function indexAction($p){
		echo 'BaseModule::indexAction';
	}
	
	public function __call($fn,$args){
		console_log("BaseModule::__call($fn,$args)");
		if(strtolower(substr($fn,-6))=='action'){			
			//return $this->showAction(array_merge( Array(P0=>substr($fn,0,-6)) ,$args));			
		}
		//...
		throw new ErrorPageException(DEBUG?("BaseModule::__call($fn,$args) -> method does not exist: ".$fn):('Page does not exist'));
	}
	
	public function requireAuth(){
		global $user;
		if(!$user->name){
			echo BR.BR.'<center>'.errorspan(translate('Nincs bejelentkezve.')).'</center>';
			js_redirect_timeout(link_for('/user/login'),3000);
			return 1;
		};
		return 0;
	}	
	
	public function requirePOST(Array $keys){
		foreach($keys as $key){
			if(!isset($_POST[$key]))
				throw new Exception('Required POST key does not exist');
		}
		return true;
	}
	
	public function requireRight($rn){
		global $user;
		$a=$user->getRight($rn,'');
		if(!$a)throw new ErrorPageException('Not allowed to access module or method');
	}
	
	public function requireUser(){
		global $user;		
		//if(!$user->name)$this->redirectTo(link_for('/user/index'));
		if(!(string)$user->name)throw new ErrorPageException('Unauthorized');
	}
	
	public function Action($p){
		$this->redirectTo(link_for('index'));
	}
}

